"""
    Contains Report class and RDSReport inheritor.
    Also contains reports loader.
"""

import os, glob, base64
import turbogears, genshi
from mnemoply import model
from mnemoply.utils import make_enum, my_import

def filemodule2name(name):
    return name.replace('.', '/') + ".html"

class Report(object):
    """
        Xml template container with additional information i.e. tag and pass_functions.
        Need for printing reports on client PC.
    """

    tag = ""
    template_module = ""
    additional_context = {}
    pass_functions = []
    fields = []

    def run(self, params):
        """
            Takes template_module from report, takes template with
            this name from special directory and renders them, also added
            pass_functions inside template.
        """

        #print "Report params", params

        loader = genshi.template.loader.TemplateLoader('.')
        template = loader.load(filemodule2name(self.template_module))

        context = dict(model=model)

        # additional context
        if callable(self.additional_context):
            addon = self.additional_context()
        else:
            addon = self.additional_context
        context.update(addon)

        # pass functions
        # TODO
        self.pass_functions = list(self.pass_functions) + [genshi.XML]
        for x in self.pass_functions:
            context[x.__name__] = x

        # import params
        context.update(params)

        #for k, v in context.items():
            #setattr(template, k, v)

        return template.generate(**context).render()

RDSReportType = make_enum(
    'WORD_MULTIPAGE',
    'WORD',
    'EXCEL',
    'EXCEL2',
)

report_type2metadata = {
    RDSReportType.WORD: '<type multipage="0">msword</type>',
    RDSReportType.WORD_MULTIPAGE: '<type multipage="1">msword</type>',
    RDSReportType.EXCEL: '<type>msexcel</type>',
    RDSReportType.EXCEL2: '<type>msexcel2</type>',
}

class RDSReport(Report):
    """
        Report with changed mime-type. Contains word/excel template inside.
    """

    outputType = "application/rds"
    template_module = ""
    report_type = RDSReportType.WORD

    def run(self, params):
        ctx = params.copy()
        vtemplate = model.File.byTag(self.tag)
        ctx['template_data'] = base64.b64encode(vtemplate.content)
        ctx['template_filename'] = vtemplate.name
        ctx['report_type_metadata'] = report_type2metadata[self.report_type]
        ctx['latest_readrds_version'] = turbogears.config.get("readrds.latest_version")
        return Report.run(self, ctx)

class Reports(object):
    """
        Loads all reports from special directory.
        Provides access to them.
    """

    def __init__(self):
        self.reports = {}
        self.loaded = False

    def loadReports(self):
        """
            Load reports from mnemoply/reports/ directory.
            Put them to `self.reports` dictionary.
        """

        reports_dir = os.path.dirname(__file__)

        for report_file in glob.glob(os.path.join(reports_dir, "*.py")):
            report_name = os.path.splitext(os.path.basename(report_file))[0]
            if report_name.startswith('_'):
                continue
            report_module = my_import("mnemoply.reports." + report_name)

            if hasattr(report_module, "exposed") and report_module.exposed is not None:
                self.register(report_module.exposed)

    def register(self, report):
        """
            Register report by themself.
        """
        self.reports[report.tag] = report

    def byTag(self, tag):
        """
            Returns report by tag.
        """
        if not self.loaded:
            self.loadReports()
        return self.reports[tag]

reports = Reports()
